<?php

namespace app\api\service\sms;
use app\common\model\AdminSmsTemplate;
use app\common\model\AdminSmsUser;
use app\common\model\AdminSmsLog;
class Send
{
    public function Sms($code = '', $Nums = '', $params = [])
    {
        $AdminSmsTemplate = new AdminSmsTemplate();
        $AdminSmsUser = new AdminSmsUser();
        $Template = $AdminSmsTemplate->where("only_num='" . $code . "' and is_delete=0")->findOrEmpty()->toArray();
        $User = $AdminSmsUser->where("id='" . $Template['user_id'] . "' and is_delete=0")->findOrEmpty()->toArray();
        switch ($Template['template_type']) {
            case 2:
                $type = 'email';
                break;
            case 3:
                $type = 'weixin';
                break;
            case 4:
                $type = 'dingding';
                break;
            default:
                $type = 'phone';
        }
        $num = ucfirst($User['num']);
        $config = !empty($User['config']) ? json_decode($User['config'], true) : [];
        $setData = [];
        foreach ($config as $k => $v) {
            $setData['config'][$v['field']] = $v['value'];
        }
        $setData['config']['nums'] = $Nums;
        $setData['config']['sign_name'] = $Template['sign_name'];
        $setData['config']['template_code'] = $Template['template_code'];
        $json = !empty($Template['template_test_json']) ? json_decode($Template['template_test_json'], true) : [];
        foreach ($json as $k => $v) {
            $setData['data'][$v['field']] = isset($params[$v['field']]) ? $params[$v['field']] : $v['value'];
        }
        $className = '\\app\api\\service\\sms\\' . $type . '\\' . $num;
        $ThatSend = new $className();
        $result = $ThatSend->Send($setData);
        $upData = [
            'id' => GetSnowID(),
            'title' => $Template['template_name'],
            'type' => $Template['template_type'],
            'receiver' => $Nums,
            'param' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'content' => $Template['template_content'],
            'send_time' => date('Y-m-d H:i:s'),
            'send_status' => $result['code'],
            'send_num' => 1,
            'result' => json_encode($result['data'], JSON_UNESCAPED_UNICODE),
        ];
        $AdminSmsLog = new AdminSmsLog();
        $AdminSmsLog->save($upData);
        return $result;
    }
}